#include <my_header.h>
#include <string.h>
#define BUF_SIZE 4096
#define OUTPUT_DIR "receive_files"

typedef struct {
    char name[256];
    int size;
    char data[BUF_SIZE];
} file_packet;

/* Usage: mkfifo 创建管道文件 */
int main(int argc, char *argv[]){
    // Create directory
    mkdir(OUTPUT_DIR, 0755);

    // Open pipe
    int fd = open("data.pipe", O_RDONLY);
    ERROR_CHECK(fd, -1, "fd2_read");

    // Create object
    file_packet packet;

    // Recv pipe
    ssize_t bytes_read = read(fd, &packet, sizeof(file_packet));
    if(bytes_read <= 0) return -1;

    // Create file
    char path[512];
    snprintf(path, sizeof(path), "%s/%s", OUTPUT_DIR, packet.name);

    // Write file
    int file_fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    ERROR_CHECK(file_fd, -1, "create file");

    write(file_fd, packet.data, sizeof(packet.data));

    close(fd);
    close(file_fd);
    return 0;
}
